version: "3.9"

x-media-volume: &media-volume ./media/:${PROJECT_PATH:-/usr/src/app}/media/

services:
  tg_bot:
    container_name: tinkoff_bot.tg_bot
    image: "${BOT_IMAGE_NAME:-tinkoff_bot.tinkoff_bot}"
    build:
      context: .
    restart: unless-stopped
    stop_signal: SIGINT
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    volumes:
      - *media-volume
    networks:
      - tinkoff_bot.postgres.network
      - tinkoff_bot.redis.network
    environment:
      - TZ=Europe/Moscow
    env_file:
      - ".env"
    command: [ "python", "-Om", "tinkoff_bot.tg_bot" ]
  redis:
    container_name: tinkoff_bot.redis
    image: redis:7.0.10-alpine
    command:
      sh -c '
      redis-server
      --appendonly yes
      --bind 0.0.0.0'
    volumes:
      - tinkoff_bot.redis.data:/data:rw
    ports:
      - "6380:6379"
    networks:
      - tinkoff_bot.redis.network
    healthcheck:
      test: [ "CMD", "redis-cli", "ping" ]
      interval: 10s
      timeout: 60s
      retries: 5
      start_period: 10s
    environment:
      - TZ=Europe/Moscow
    env_file:
      - ".env"
  postgres_migration:
    image: "${BOT_IMAGE_NAME:-tinkoff_bot.tinkoff_bot}"
    container_name: tinkoff_bot.postgres_migration
    build:
      context: .
    restart: on-failure
    depends_on:
      postgres:
        condition: service_healthy
    networks:
      - tinkoff_bot.postgres.network
    volumes:
      - .:${PROJECT_PATH:-/usr/src/app}
      - ./alembic.ini:${PROJECT_PATH:-/usr/src/app}/alembic.ini:ro
    env_file:
      - ".env"
    command: [ "python", "-m", "alembic", "upgrade", "head" ]
  postgres:
    container_name: tinkoff_bot.postgres
    image: "postgres:15-alpine"
    hostname: tinkoff_bot.postgres
    restart: unless-stopped
    expose:
      - "5432"
    ports:
      - "${DB__PORT:-5432}:5432"
    networks:
      - tinkoff_bot.postgres.network
    environment:
      POSTGRES_PASSWORD: $DB__PASSWORD
      POSTGRES_USER: $DB__USER
      POSTGRES_DB: $DB__NAME
    volumes:
      - tinkoff_bot.postgres.data:/var/lib/postgresql/users:rw
    healthcheck:
      test: [ "CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}" ]
      interval: 10s
      timeout: 60s
      retries: 5
      start_period: 10s

volumes:
  tinkoff_bot.postgres.data: {}
  tinkoff_bot.redis.data: {}

networks:
  tinkoff_bot.postgres.network: {}
  tinkoff_bot.redis.network: {}
